<?php
/**
 * DuoLam 文件
 *
 * @author Mo yi <root@imoi.cn>
 * @link   http://www.imoi.cn
 * @copyright Copyright &copy; 2010-2012 DuoLam Software LLC
 * @license http://www.imoi.cn/license/
 * @version $Id: duolam.php 2799 2012-03-30 13:35:54Z Mo.yi $
 * @package system
 * @since 1.0
 */

class DuoLam
{
    /**
     * 类文件地图，用到的时候会被自动加载
     */
    public  static $classMap = array();

    public  static $alias    = array();

    public  static $import   = array();

    public  static $config   = array();

    private static $_files   = array();

    private static $_app;


    /**
     * @return 返回框架版本号
     */
    public static function version()
    {
        return '2.0.0';
    }

    /**
     * 创建应用程序接口
     * @param mixed  $config 应用程序配置信息
     * @param string $type   应用程序类型：(web|command) 默认web
     * @return dpApplication对象
     */
    public static function createApplication($config = null ,$type = 'web')
    {
        self::$config = $config;
        return new dpApplication($config,$type);
    }

	/**
	 * 返回应用程序创建的组件，以单件模式实例化组件。
	 * @return 实例化的对象
	 */
	public static function app()
	{
		return self::$_app;
	}

    public static function setApp($app)
    {
        if (self::$_app === null) self::$_app = $app;
    }

    /**
     * 载入文件或者指定载入某个目录的文件
     * 如果是文件则直接载入，如果是目录，则延迟加载
     * @param string $alias  文件或者目录的路径
     */
    public static function import($alias,$r=false)
    {
        if (empty($alias)) return false;

        $suffix = substr($alias,-1);

        if (($pos = strrpos($alias, ':')) !== false) {
            $alia = substr($alias, 0, $pos);
            $file = substr($alias, $pos + 1);
            if (isset(D::$alias[$alia]) && in_array(substr(D::$alias[$alia].$file,0,-1), D::$import)) {
                    return true;
            }
        }

        if (isset($alia)) {
            if (isset(D::$alias[$alia]))
                $path = D::$alias[$alia] . $file;
            else
                $path = $alias;
        } else $path = $alias;

        $path = str_replace('.', DS, $path);

        if ($suffix == '*')
            D::$import[] = substr($path, 0, -1);
        else if (is_file($path.'.php') && !in_array($path, self::$_files)) {
            self::$_files[] = $path;
            if ($r) return require($path . '.php');
            else require($path . '.php');
        }
    }

    /**
     * 自动加载器
     * @param $classname 文件名
     */
    public static function autoload($classname)
    {
        $_coreClass = self::_coreClass();

        if (!empty(D::$classMap)) {
        	foreach (D::$classMap as $v) {
        		unset(D::$classMap[$v]);
        		D::import($v);
        	}
        }

       	if (isset($_coreClass[$classname])) {
            include(DP_PATH . $_coreClass[$classname]);
        } else if (!empty(D::$import)) {
			foreach (D::$import as $v) {
				$file = $v . $classname .'.php';
				if(is_file($file)) {
                    class_exists($classname) or require($file);
                }
			}
        } else dpException::error($classname . '类文件不存在！');
    }

	/**
	 * 返回应用程序URL根目录
	 */
    public static function homeUrl()
	{
		$_self = empty($_SERVER['PHP_SELF']) ? $_SERVER['SCRIPT_NAME'] : $_SERVER['PHP_SELF'];
		$_self = explode('/',$_self);
		$key   = array_search('index.php',$_self);
		$self  = null;
		for ($i = $key; $i >= 0; $i--) {
			if ($_self[$i] !== 'index.php')
                $self = $_self[$i] . '/' .  $self;
			unset($_self[$i]);
		}
		return $self;
	}

	/**
	 * 注册SPL自动加载
	 * @param $class    类名
	 * @param $enabled  注册SPL开关
	 */
    public static function registerAutoload($class = 'D', $enabled = true)
    {
        if (!function_exists('spl_autoload_register')) {
            require_once DP_PATH . '/core/dpException.php';
            throw new dpException('你的PHP版本不支持SPL自动加载的注册！');
        }

        if ($enabled === true) {
            spl_autoload_register(array($class, 'autoload'));
        } else {
            spl_autoload_unregister(array($class, 'autoload'));
        }
    }

    /**
     * 动态设置路径别名
     * 如果设置一个，第二个参数也要填写。
     * 如果设置多个，第一个参数为数组，key为别名，值为路径
     * @param $alias 别名
     * @param $path  真实路径
     */
    public static function setPathAlias($alias,$path = null)
    {
        if (is_array($alias)) {
            foreach ($alias as $a_name => $a_path) {
                D::$alias[$a_name] = $a_path;
            }
        } else {
        	D::$alias[$alias] = $path;
        }
    }

    /**
     * 删除一个已设置的路径别名
     * @param $aliasName  路径别名
     * @param boolean     返回布尔值，如果成功返回true
     */
	public static function unsetPathAlias($aliasName)
	{
		if (isset(D::$alias[$aliasName])) {
			unset(D::$alias[$aliasName]);
			return true;
		} else return false;
	}

    /**
     * 输出错误信息
     * @param string $msg
     */
    public static function error($msg, $log = false)
    {
        dpException::error($msg,false,array(),true, $log);
    }

    /**
     * 手动记录系统日志
     * @param string $info 日志信息
     */
    public static function log($info)
    {
        dpLoging::writeLog($info);
    }

     /**
     * 创建URL地址
     * @param string $route URL路由
     * @param array  $params URL参数
     * @param string $ampersand 参数分隔符，在URL模式为path时有效
     * @return string 根据参数返回创建好的url
     */
    public static function cu($route, $params = array(), $ampersand = null)
    {
        if (!empty($params) && !is_array($params)) {
            $param  = explode('|', $params);
            $params = '';
            foreach ($param as $gn => $gv) {
                $temp = explode('=', $gv);
                $params[$temp[0]] = $temp[1];
            }
        }
        return dpUrlConfig::createUrl($route, $params, $ampersand);
    }

    /**
     * 创建URL地址
     * @param string $route URL路由
     * @param array  $params URL参数
     * @param string $ampersand 参数分隔符，在URL模式为path时有效
     * @return string 根据参数返回创建好的url
     */
    public static function createUrl($route, $params = array(), $ampersand = null)
    {
        return D::cu($route, $params, $ampersand);
    }

    /**
     * 获取已经设置的别名路径，包括配置文件里的import
     * @param $alias 指定一个别名，获取某个别名的真实路径
     * @return array 返回设置的别名和路径
     */
    public static function getPathAlias($alias = null)
    {
        if (isset($alias) and isset(D::$alias[$alias]))
            return D::$alias[$alias];
        else
            return D::$alias;
    }

	/**
	 * 框架核心类地图
	 * @return array
	 */
    private static function _coreClass()
    {
        return array(
            /**
             * base  目录
             */
            'dpApplication'    => '/base/dpApplication.php',
            'dpAccess'         => '/base/dpAccess.php',
            'dpUrlConfig'      => '/base/dpUrlConfig.php',
            /**
             * cache 目录
             */
            'dpCache'          => '/cache/dpCache.php',
            'dpFileCache'      => '/cache/dpFileCache.php',
            'dpApcCache'       => '/cache/dpApcCache.php',
            'dpMemCache'       => '/cache/dpMemCache.php',
            'dpXCache'         => '/cache/dpXCache.php',
            /**
             * core  目录
             */
            'dpException'      => '/core/dpException.php',
            'dpComponent'      => '/core/dpComponent.php',
			'dpLoging'		   => '/core/dpLoging.php',
            /**
             * db    目录
             */
            'dpDbConnect'      => '/db/dpDbConnect.php',
            'dpDbCommand'      => '/db/dpDbCommand.php',
            'dpActiveRecord'   => '/db/ar/dpActiveRecord.php',
            'dpActiveFinder'   => '/db/ar/dpActiveFinder.php',
            'dpMysqlDriver'    => '/db/drivers/dpMysqlDriver.php',
            'dpMysqliDriver'   => '/db/drivers/dpMysqliDriver.php',
            'dpPdoDriver'      => '/db/drivers/dpPdoDriver.php',
            'dpSchema'         => '/db/schema/dpSchema.php',
            'dpMysqlSchema'    => '/db/schema/dpMysqlSchema.php',
            'dpMssqlSchema'    => '/db/schema/dpMssqlSchema.php',
            'dpSqliteSchema'   => '/db/schema/dpSqliteSchema.php',
			/**
			 * view  目录
			 */
			'dpView'		   => '/view/dpView.php',
            'dpWidget'         => '/view/dpWidget.php',
			'dpViewRender'	   => '/view/renders/dpViewRender.php',
			'dpModuleRender'   => '/view/renders/dpModuleRender.php',
            /**
             * web   目录
             */
            'dpControl'        => '/web/dpControl.php',
            'dpModule'         => '/web/dpModule.php',
            'dpAction'         => '/web/dpAction.php',
            /**
             * web.auth   目录
             */
            'dpAuthInstall'    => '/web/auth/dpAuthInstall.php',
            'dpAuth'           => '/web/auth/dpAuth.php',
            'dpAuthRole'       => '/web/auth/dpAuthRole.php',
            'dpAuthBehavior'   => '/web/auth/dpAuthBehavior.php',
            'dpAuthRule'       => '/web/auth/dpAuthRule.php',
            'dpAuthFilter'     => '/web/auth/dpAuthFilter.php',
            'dpUser'           => '/web/auth/dpUser.php',
            'dpUserIdentity'   => '/web/auth/dpUserIdentity.php',
			/**
			 * web.helper 目录
			 */
			'dpRequest'		   => '/web/helper/dpRequest.php',
			'dpImage'		   => '/web/helper/dpImage.php',
			'dpCookie'		   => '/web/helper/dpCookie.php',
			'dpSession'		   => '/web/helper/dpSession.php',
			'dpEncrypt'		   => '/web/helper/dpEncrypt.php',
			'dpCurl'		   => '/web/helper/dpCurl.php',
			'dpCsv'			   => '/web/helper/dpCsv.php',
			'dpExcel'		   => '/web/helper/dpExcel.php',
			'dpFtp'			   => '/web/helper/dpFtp.php',
			'dpPinyin'		   => '/web/helper/dpPinyin.php',
			'dpText'		   => '/web/helper/dpText.php',
			'dpTree'		   => '/web/helper/dpTree.php',
			'dpWsdl'		   => '/web/helper/dpWsdl.php',
			'dpZip'			   => '/web/helper/dpZip.php',
			'dpJson'		   => '/web/helper/dpJson.php',
			'dpScript'		   => '/web/helper/dpScript.php',
			'dpUpload'		   => '/web/helper/dpUpload.php',
			'dpPage'		   => '/web/helper/dpPage.php',
            'dpForm'           => '/web/helper/dpForm.php',
            'dpIp'             => '/web/helper/dpIp.php',
            'dpMail'           => '/web/helper/dpMail.php',
            'dpSmtp'           => '/web/helper/dpSmtp.php',
            'dpHook'           => '/web/helper/dpHook.php',
            'dpLottery'        => '/web/helper/dpLottery.php',

            'dpExcelReader'    => '/web/excelread/dpExcelReader.php',
        );
    }
}

/**
 * 多语言方法
 * @param string $key 多语言key
 * @param string $filename 多语言文件
 * @param string $lang 语言
 */
function t($key, $filename, $lang = 'zh_cn')
{
    $file = APP_PATH.DS.'app'.DS.'language'.DS.$lang.DS.$filename;
    if (is_file($file)) {
        $language = require($file);
        return isset($language[$key]) ? $language[$key] : null;
    }
    return false;
}

?>